import axios from "axios";
// @ts-ignore
import cookie from "js-cookie";
import router from "@/router";

const httpService = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 10000
});

//将token放请求头
httpService.interceptors.request.use((config: any) => {
    config.headers.token = cookie.get("sysToken")
    return config
}, error => {
    return Promise.reject(error)
})

//请求拦截器
httpService.interceptors.request.use(
    (config) => {
        config.headers = {
            Authorization: 'token'
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

//响应拦截器
httpService.interceptors.response.use(
    (response) => {
        return response
    },
    (error) => {
        if (error.response.status === 401) {
            alert("登录过期，请重新登录!")
            cookie.remove("sysToken")
            cookie.remove("sysUser")
            router.push("/login").then(r => {
                return r
            })
            console.log("登录过期，请重新登录！")
        } else if (error.response.status === 403) {
            console.log("重定向错误！")
        } else if (error.response.status === 404) {
            console.log("页面不存在！")
        } else {
            console.log("异常错误，请联系管理员！")
        }
        return Promise.resolve({})
    }
)

export default httpService